package com.scrum.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.scrum.Object.Catalog;
import com.scrum.Object.File_Process;
import com.scrum.Object.Post;


/**
 * Servlet implementation class New_Post
 */
@WebServlet("/post/new_post")
@MultipartConfig
public class New_Post extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public New_Post() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String filePath = getServletContext().getInitParameter("post_file_upload"); 
	    Part filePart = request.getPart("browse_image"); // Retrieves <input type="file" name="file">
	    String filename = File_Process.getFilename(filePart);
	    InputStream filecontent = filePart.getInputStream();
	    OutputStream  outputStream = new FileOutputStream(new File(filePath+ File.separator + filename));
	    int read = 0;
	    byte[] bytes = new byte[1024];

		while ((read = filecontent.read(bytes)) != -1) {
			outputStream.write(bytes, 0, read);
		}
		String title = request.getParameter("title");
		String catalog = request.getParameter("catalog");
		String description = request.getParameter("description");
		//usersignin
		int user_id = 1;
		try {
		int catalog_id = Catalog.getId(catalog);
		if (catalog_id != -1){
				Post post = Post.addpost(title, catalog_id , filename, description, user_id);
				if (post == null) {
//					response.sendRedirect("addquestion.jsp?class="+);
			}
			else {
//					response.sendRedirect("bankquestion.jsp?class="+standard_id);
			}
		}
			} catch (ClassNotFoundException | SQLException e) {
				e.printStackTrace();
			}
//			
		
		}
	}
	

